<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/11/25
 * Time: 9:58
 */
namespace app\api\controller\handleData\client;

use app\api\controller\BaseController;
use app\common\exception\CustomException;
use think\Db;

class ClientController extends BaseController
{
    /**
     * @name 主机资源上传
     * @author wx
     * @date 2020/11/25 9:59
     */
    public function resource()
    {
        //接收参数
        $data = file_get_contents('php://input', 'r');

        $data = json_decode($data, true);
        $info = json_encode($data['data']);

        //修改数据
        Db::name('host_hardware')->where('host_id', $data['hostid'])->update(['info' => $info]);
        return $this->jsonOutPut();
    }

    /**
     * @name 主机端口上传
     * @author wx
     * @date 2020/11/25 11:06
     */
    public function port()
    {
        set_time_limit(0);

        //1. 接收参数
        $data = file_get_contents('php://input', 'r');

        $this->addRuntimeLog('../runtime/clientUploadPort.log', $data);
        $data = json_decode($data, true);



        $portData = $data['data'];
        $hostId = $data['hostid'];

        //查询数据
        $hostCount = Db::name('host')->where('id', $hostId)->where('hostkey', $data['hostkey'])->count();
        if(!$hostCount){
            throw new CustomException('该主机不存在', 202);
        }

        //2. 删除当前主机所有开放端口
        Db::name('host_port')->where('host_id', $hostId)->delete();

        //构造数据
        $limit = 140000;
        $startId = $hostId * $limit - 139999;

        //3. 遍历端口详情
        foreach ($portData as $k => $v){

            if ($v['ip'] == '127.0.0.1' || $v['ip'] == '::1') {
                //除去本地访问端口
                continue;
            }
            $tmp['id'] = $k + $startId;
            $tmp['host_id'] = $hostId;
            $tmp['protocols'] = $v['Proto'];
            $tmp['port'] = $v['Port'];
            $tmp['ip'] = $v['ip'];
            $tmp['process'] = $v['path'];
            $tmp['guise'] = isset($v['guise']) ? $v['guise'] : 0;

            $insertData[] = $tmp;
        }

        //4. 入库
        if(!empty($insertData)){
            $limit = 1000;//分批插入
            Db::name('host_port')->insertAll($insertData, true, $limit);
        }

        return $this->jsonOutPut();
    }
}